// pages/date/index.js
const { dateService } = require('../../services/index');
const app = getApp();
const { formatTime, getRelativeTime } = require('../../utils/util');

Page({
  data: {
    dateList: [],           // 日期列表
    upcomingDates: [],     // 即将到来的日期
    isLoading: false,      // 加载状态
    activeTab: 0,         // 当前标签页
    userInfo: null,       // 用户信息
    showActionSheet: false // 是否显示操作菜单
  },

  onLoad() {
    // 开发模式下确保情侣信息已设置
    if (app.devConfig.enabled && !app.globalData.coupleInfo) {
      app.globalData.coupleInfo = app.devConfig.mockData.coupleInfo;
    }
    
    // 检查登录和情侣状态
    if (!app.routeInterceptor()) return;
    
    this.setData({
      userInfo: app.globalData.userInfo,
      // 设置开发模式标志，用于WXML条件判断
      isDevMode: app.devConfig.enabled,
      hasCoupleInfo: !!app.globalData.coupleInfo
    });
    
    // 加载日期数据
    this.loadDateData();
  },

  onShow() {
    // 每次显示页面时检查数据更新
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        // 更新开发模式状态
        isDevMode: app.devConfig.enabled,
        hasCoupleInfo: !!app.globalData.coupleInfo
      });
    }
  },

  // 加载日期数据
  async loadDateData() {
    // 开发模式下直接加载模拟数据，跳过情侣检查
    if (app.devConfig.enabled) {
      this.setData({ isLoading: true });
      
      setTimeout(() => {
        const mockDates = this.getMockDateData();
        this.setData({
          dateList: mockDates,
          upcomingDates: this.getUpcomingDates(mockDates),
          isLoading: false
        });
      }, 500);
      return;
    }
    
    // 生产环境：检查情侣状态
    if (!app.globalData.coupleInfo) {
      this.setData({ dateList: [], upcomingDates: [] });
      return;
    }
    
    this.setData({ isLoading: true });
    
    try {
      // 生产环境：调用API获取数据
      const dateList = await dateService.getCoupleImportantDates(
        app.globalData.coupleInfo.id
      );
      
      const upcomingDates = await dateService.getUpcomingReminders(
        app.globalData.coupleInfo.id,
        30
      );
      
      this.setData({
        dateList: dateList || [],
        upcomingDates: upcomingDates || [],
        isLoading: false
      });
    } catch (error) {
      console.error('加载日期数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ isLoading: false });
    }
  },

  // 开发模式下的模拟数据
  getMockDateData() {
    const now = new Date();
    const currentYear = now.getFullYear();
    
    return [
      {
        id: 1,
        name: '恋爱纪念日',
        dateType: 'anniversary',
        baseDate: `${currentYear}-06-15`,
        isYearly: true,
        notes: '我们在一起的日子',
        daysUntil: this.calculateDaysUntil(`${currentYear}-06-15`)
      },
      {
        id: 2,
        name: '她的生日',
        dateType: 'birthday',
        baseDate: `${currentYear}-09-20`,
        isYearly: true,
        notes: '祝她生日快乐',
        daysUntil: this.calculateDaysUntil(`${currentYear}-09-20`)
      },
      {
        id: 3,
        name: '我的生日',
        dateType: 'birthday',
        baseDate: `${currentYear}-08-20`,
        isYearly: true,
        notes: '祝我生日快乐',
        daysUntil: this.calculateDaysUntil(`${currentYear}-08-20`)
      },
      {
        id: 4,
        name: '情人节',
        dateType: 'holiday',
        baseDate: `${currentYear}-02-14`,
        isYearly: true,
        notes: '浪漫的情人节',
        daysUntil: this.calculateDaysUntil(`${currentYear}-02-14`)
      },
      {
        id: 5,
        name: '圣诞节',
        dateType: 'holiday',
        baseDate: `${currentYear}-12-25`,
        isYearly: true,
        notes: '圣诞快乐',
        daysUntil: this.calculateDaysUntil(`${currentYear}-12-25`)
      },
      {
        id: 6,
        name: '第一次约会',
        dateType: 'special',
        baseDate: '2024-05-01',
        isYearly: false,
        notes: '难忘的第一次约会',
        daysUntil: this.calculateDaysUntil('2024-05-01')
      },
      {
        id: 7,
        name: '国庆节',
        dateType: 'holiday',
        baseDate: `${currentYear}-10-01`,
        isYearly: true,
        notes: '国庆节快乐',
        daysUntil: this.calculateDaysUntil(`${currentYear}-10-01`)
      },
      {
        id: 8,
        name: '万圣节',
        dateType: 'holiday',
        baseDate: `${currentYear}-10-31`,
        isYearly: true,
        notes: '不给糖就捣蛋',
        daysUntil: this.calculateDaysUntil(`${currentYear}-10-31`)
      },
      {
        id: 9,
        name: '下个月纪念日',
        dateType: 'anniversary',
        baseDate: `${currentYear}-10-15`,
        isYearly: true,
        notes: '每月纪念',
        daysUntil: this.calculateDaysUntil(`${currentYear}-10-15`)
      }
    ];
  },

  // 计算距离日期的天数
  calculateDaysUntil(targetDate) {
    const today = new Date();
    const target = new Date(targetDate);
    const timeDiff = target.getTime() - today.getTime();
    return Math.ceil(timeDiff / (1000 * 3600 * 24));
  },

  // 获取即将到来的日期
  getUpcomingDates(dates) {
    return dates
      .filter(date => date.daysUntil >= 0 && date.daysUntil <= 30)
      .sort((a, b) => a.daysUntil - b.daysUntil);
  },

  // 切换标签页
  onTabChange(e) {
    this.setData({
      activeTab: e.detail.index
    });
  },

  // 导航到添加日期页面
  navToAddDate() {
    wx.navigateTo({
      url: '/pages/date/add'
    });
  },

  // 查看日期详情
  viewDateDetail(e) {
    const { id } = e.currentTarget.dataset;
    const date = this.data.dateList.find(item => item.id === id);
    
    wx.showModal({
      title: date.name,
      content: `日期: ${formatTime(date.baseDate, 'YYYY年MM月DD日')}
类型: ${this.getDateTypeText(date.dateType)}
${date.isYearly ? '每年重复' : '单次日期'}
备注: ${date.notes || '无'}`,
      showCancel: false
    });
  },

  // 显示操作菜单
  showActionMenu() {
    this.setData({ showActionSheet: true });
  },



  // 编辑日期
  editDate(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/date/add?id=${id}`
    });
    // 关闭操作菜单（如果有）
    if (this.data.showActionSheet) {
      this.setData({ showActionSheet: false });
    }
  },

  // 删除日期
  deleteDate(e) {
    const { id } = e.currentTarget.dataset;
    const date = this.data.dateList.find(item => item.id === id);
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${date.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.performDelete([id]);
        }
      }
    });
    // 关闭操作菜单（如果有）
    if (this.data.showActionSheet) {
      this.setData({ showActionSheet: false });
    }
  },



  // 执行删除操作
  performDelete(ids) {
    // 开发模式下直接操作本地数据
    if (app.devConfig.enabled) {
      const dateList = this.data.dateList.filter(item => !ids.includes(item.id));
      const upcomingDates = this.data.upcomingDates.filter(item => !ids.includes(item.id));
      
      this.setData({
        dateList,
        upcomingDates
      });
      
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
      return;
    }
    
    // 生产环境：调用API删除
    this.setData({ isLoading: true });
    
    Promise.all(ids.map(id => dateService.deleteDate(id)))
      .then(() => {
        return this.loadDateData();
      })
      .then(() => {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        this.setData({
          isLoading: false
        });
      })
      .catch(error => {
        console.error('删除失败:', error);
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        });
        this.setData({ isLoading: false });
      });
  },

  // 获取日期类型文本
  getDateTypeText(type) {
    const types = {
      anniversary: '纪念日',
      birthday: '生日',
      holiday: '节日',
      other: '其他'
    };
    return types[type] || '其他';
  },

  // 导航到情侣绑定页面
  navToCoupleBind() {
    wx.navigateTo({
      url: '/pages/couple/bind'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadDateData().finally(() => {
      wx.stopPullDownRefresh();
    });
  }
});